class Solution {
public:
    vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) {
        // refine the edges
        vector<unordered_set<int>> adjusted_edges(n);
        for(auto m: edges)
        {
            adjusted_edges[m.first].insert(m.second);
            adjusted_edges[m.second].insert(m.first);
        }
        
        // corner case
        if(n == 1)
            return {0};
        
        // get the layer of leaves
        vector<int> current_layer;
        for (int i = 0; i < n; i++)
            if (adjusted_edges[i].size() == 1)
                current_layer.push_back(i);
        
        // bfs
        while(true)
        {
            vector<int> next;
            for(int i : current_layer)
            {
                for(int j : adjusted_edges[i])
                {
                    adjusted_edges[j].erase(i);
                    if(adjusted_edges[j].size() == 1) // 关键！与上一行在循环中有联动
                        next.push_back(j);
                }
            }
            if(next.empty())
                return current_layer;
            current_layer = next;
        }
            
    }
};
